import Vue from 'vue'
import { Promise } from 'es6-promise'
import apiGoods from '../../api/goods'

const state = {
  data: [],
}

// getters
const getters = {
  getGoods: (state) => {
    return state.data
  }
}

// actions
const actions = {
  initGoods({ commit, state }, obj) {
    return new Promise((resolve, reject) => {
      if (state.data.length) {
        resolve(state.data)
      } else {
        apiGoods.getGoods(obj.sellerId, (reData) => {
          if (reData && reData.length) {
            commit('initGoods', reData)
            resolve(reData)
          } else {
            reject({ errno: 1, msg: '请求失败' })
          }
        })
      }
    })
  },
}

// mutations
const mutations = {
  initGoods(state, returnData) {
    Vue.set(state, 'data', returnData)
  },
  addCart(state, target) {
    state.data.forEach((good, index) => {
      good.foods.forEach((food) => {
        if (food === target) {
          if (!(food.count > 0)) {
            Vue.set(food, 'count', 1)
          } else {
            /* eslint-disable */
            food.count++
          }
        }
      })
    })
  },
  descreaseCart(state, target) {
    state.data.forEach((good, index) => {
      good.foods.forEach((food) => {
        if (food === target) {
          if (food.count > 0) {
            /* eslint-disable */
            food.count--
          }
        }
      })
    })
  },
  clearSelectFoods(state) {
    state.data.forEach((good, index) => {
      good.foods.forEach((food) => {
        if (food.count > 0) {
          /* eslint-disable */
          food.count = 0
        }
      })
    })
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations,
}
